package com.youlai.system.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.system.common.enums.StatusEnum;
import com.youlai.system.common.exception.BusinessException;
import com.youlai.system.common.result.ResultCode;
import com.youlai.system.model.entity.Product;
import com.youlai.system.model.form.ProductFrom;
import com.youlai.system.model.query.ProductPageQuery;
import com.youlai.system.model.vo.ProductPageVo;
import com.youlai.system.service.ProductService;
import com.youlai.system.mapper.ProductMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
* @author zzps
* @description 针对表【t_product(商品表)】的数据库操作Service实现
* @createDate 2024-03-11 22:24:49
*/
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product>
    implements ProductService{

    @Override
    public IPage<ProductPageVo> getProductPageList(ProductPageQuery productPageQuery) {
        // 封装分页参数
        Page<ProductPageVo> page = new Page<>(productPageQuery.getPageNum(), productPageQuery.getPageSize());
        // 查询数据
        return baseMapper.getProductPageList(page, productPageQuery);
    }

    @Override
    public boolean addProduct(ProductFrom productForm) {
        // 封装商品数据
        Product product = new Product();
        BeanUtils.copyProperties(productForm, product);
        // 新增商品
        return save(product);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDeleteProduct(List<Long> ids) {
        // 批量删除商品
        return removeByIds(ids);
    }

    @Override
    public boolean upOrDownProduct(Long id, Integer status) {
        // 判断商品状态是否合法
        if (!Objects.equals(status, StatusEnum.ENABLE.getValue()) && !Objects.equals(status, StatusEnum.DISABLE.getValue())) {
            throw new BusinessException(ResultCode.PARAM_VALID_ERROR);
        }
        // 更新商品状态
        return lambdaUpdate().eq(Product::getId, id).set(Product::getStatus, status).update();
    }

    @Override
    public boolean deleteProduct(Long id) {
        return removeById(id);
    }

    @Override
    public boolean updateProduct(ProductFrom productForm) {
        // 封装商品数据
        Product product = new Product();
        BeanUtils.copyProperties(productForm, product);
        // 更新商品
        return updateById(product);
    }

    @Override
    public ProductPageVo getProductById(Long id) {
        // 查询商品详情
        return this.baseMapper.getProductById(id);
    }
}




